class PhoneStateMonitor {
  constructor() {
    this.mainActivity = plus.android.runtimeMainActivity();
    this.telephonyManager = null;
    this.phoneStateListener = null;
    this.outgoingCallReceiver = null;
    this.isListening = false;
  }

  // 初始化监听
  async startListening(callback) {
    const hasPermission = await requestPermissions();
    if (!hasPermission) return;

    // 1. 监听来电和通话状态变化
    this.telephonyManager = plus.android.importClass("android.telephony.TelephonyManager");
    const tm = this.mainActivity.getSystemService(this.telephonyManager.TELEPHONY_SERVICE);
    
    const PhoneStateListener = plus.android.importClass("android.telephony.PhoneStateListener");
    this.phoneStateListener = new PhoneStateListener();
    
    // 重写 onCallStateChanged 方法
    plus.android.implements(this.phoneStateListener, "android.telephony.PhoneStateListener", {
      onCallStateChanged: (state, incomingNumber) => {
        switch (state) {
          case this.telephonyManager.CALL_STATE_RINGING:
            callback({ type: "incoming", state: "ringing", number: incomingNumber });
            break;
          case this.telephonyManager.CALL_STATE_OFFHOOK:
            callback({ type: "calling", state: "connected" });
            break;
          case this.telephonyManager.CALL_STATE_IDLE:
            callback({ type: "call_end", state: "idle" });
            break;
        }
      }
    });
    
    tm.listen(this.phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);

    // 2. 监听去电（区分 Android 版本）
    this.registerOutgoingCallReceiver(callback);
    this.isListening = true;
  }

  // 注册去电广播接收器
  registerOutgoingCallReceiver(callback) {
    const IntentFilter = plus.android.importClass("android.content.IntentFilter");
    const filter = new IntentFilter();
    
    // Android 9 及以下使用 ACTION_NEW_OUTGOING_CALL
    // Android 10+ 需通过 CALL_LOG 或 ROLE_CALL_SCREENING（此处简化处理）
    filter.addAction("android.intent.action.NEW_OUTGOING_CALL");
    
    this.outgoingCallReceiver = plus.android.implements("android.content.BroadcastReceiver", {
      onReceive: (context, intent) => {
        const action = intent.getAction();
        if (action === "android.intent.action.NEW_OUTGOING_CALL") {
          const phoneNumber = intent.getStringExtra("android.intent.extra.PHONE_NUMBER");
          callback({ type: "outgoing", number: phoneNumber });
        }
      }
    });
    
    this.mainActivity.registerReceiver(this.outgoingCallReceiver, filter);
  }

  // 停止监听并释放资源
  stopListening() {
    if (!this.isListening) return;
    
    // 注销监听器和广播
    this.telephonyManager.listen(this.phoneStateListener, 0);
    this.mainActivity.unregisterReceiver(this.outgoingCallReceiver);
    
    this.isListening = false;
    this.phoneStateListener = null;
    this.outgoingCallReceiver = null;
  }
}

// 导出实例
export default new PhoneStateMonitor();